package com.remainder.oss.ali.server;

import org.springframework.stereotype.Component;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.auth.sts.AssumeRoleRequest;
import com.aliyuncs.auth.sts.AssumeRoleResponse;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.remainder.oss.ali.core.OssStsProperties;
import com.remainder.oss.s3.server.OssTemplateImpl;

import lombok.SneakyThrows;

/**
 * 阿里OSS模板（扩展STS） 详情见：https://help.aliyun.com/document_detail/100624.html
 *
 * @author qiaomingzhi
 * @date 2023/4/25
 */
@Component
public class OssAliTemplateImpl extends OssTemplateImpl {

    /**
     * 阿里STS相关配置
     */
    private final OssStsProperties ossStsProperties;

    public OssAliTemplateImpl(OssStsProperties ossStsProperties) {
        this.ossStsProperties = ossStsProperties;
    }

    /**
     * 获取 STS 临时访问凭证
     */
    @Override
    @SneakyThrows
    public AssumeRoleResponse getScrip() {
        String accessKey = ossStsProperties.getStsAccessKey();
        String accessKeySecret = ossStsProperties.getStsSecretKey();
        String endpoint = ossStsProperties.getStsEndpoint();
        String roleArn = ossStsProperties.getRoleArn();
        String roleSessionName = ossStsProperties.getRoleSessionName();
        long durationSeconds = ossStsProperties.getDurationSeconds();

        String regionId = "";
        // 添加endpoint。适用于Java SDK 3.12.0以下版本。
        DefaultProfile.addEndpoint("", regionId, "Sts", endpoint);
        IClientProfile profile = DefaultProfile.getProfile(regionId, accessKey, accessKeySecret);
        DefaultAcsClient client = new DefaultAcsClient(profile);
        final AssumeRoleRequest request = new AssumeRoleRequest();
        // 适用于Java SDK 3.12.0以下版本。
        request.setMethod(MethodType.POST);
        request.setRoleArn(roleArn);
        request.setRoleSessionName(roleSessionName);
        request.setDurationSeconds(durationSeconds);

        return client.getAcsResponse(request);
    }

}
